package com.dyh.quickdemozwei.controller.http;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpContext {

	public static final Charset PREFERED_CHARSET = Charset.forName("utf-8");
	
	private Charset charset = PREFERED_CHARSET;
	private Charset readCharset = PREFERED_CHARSET;
	private String contentType = null;
	private int connectTimeout = 15000;
	private int readTimeout = 15000;
	
	private Map<String, String> headers = null;
	
	private Map<String, List<String>> params = null;
	
	public Map<String, String> getHeaders() {
		return this.headers;
	}
	
	public Map<String, List<String>> getParams() {
		return this.params;
	}
	
	public void addHeader(String name, String val) {
		name = name.toLowerCase();
		if(headers == null) headers = new HashMap<String, String>();
		headers.put(name, val);
	}
	
	public void removeHeader(String name) {
		name = name.toLowerCase();
		if(headers == null) return;
		headers.remove(name);
	}
	
	public void addParams(String name, String val) {
		if(params == null) params = new HashMap<String, List<String>>();
		List<String> paramVals = params.get(name);
		if(paramVals == null) {
			paramVals = new ArrayList<String>();
			params.put(name, paramVals);
		}
		
		if(!paramVals.contains(val)) {
			paramVals.add(val);
		}
	}
	
	public void removeParam(String name) {
		if(params == null) return;
		params.remove(name);
	}
	
	public void removeParam(String name, String val) {
		if(params == null) return;
		List<String> paramVals = params.get(name);
		if(paramVals == null) return;
		paramVals.remove(val);
	}
	
	public Charset getReadCharset() {
		return readCharset == null ? PREFERED_CHARSET : readCharset;
	}
	public void setReadCharset(Charset readCharset) {
		this.readCharset = readCharset;
	}
	public Charset getCharset() {
		return charset == null ? PREFERED_CHARSET : charset;
	}
	public void setCharset(Charset charset) {
		this.charset = charset;
	}
	public void setCharset(String charset) {
		this.charset = Charset.forName(charset);
	}
	public int getConnectTimeout() {
		return connectTimeout;
	}
	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}
	public int getReadTimeout() {
		return readTimeout;
	}
	public void setReadTimeout(int readTimeout) {
		this.readTimeout = readTimeout;
	}
	public String getContentType() {
		return contentType == null ? "application/octet-stream" : contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
}